package com.able.concurrency.t4;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @author abel.he
 * @data 2018/10/25 15:32
 * @describe LinkedBlockiingQueue 阻塞队列，队列容量不足自动阻塞，队列数量为0自动阻塞
 */
public class Test4_LinkedBlockingQueue {

     final BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>();

    final Random random = new Random(100000);

    public static void main(String[] args) {
        final Test4_LinkedBlockingQueue test4_linkedBlockiingQueue = new Test4_LinkedBlockingQueue();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        test4_linkedBlockiingQueue.blockingQueue.put("value:" + test4_linkedBlockiingQueue.random.nextInt());
                        test4_linkedBlockiingQueue.blockingQueue.put("value:" + test4_linkedBlockiingQueue.random.nextInt());
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "producer").start();

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            System.out.println(Thread.currentThread().getName() + " - " + test4_linkedBlockiingQueue.blockingQueue.take());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "consumer " + i).start();
        }

    }

}
